package com.sunnada.edu.system.pub.util;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.sunnada.edu.system.pub.common.Constants;

/***
 * explain 公用工具类
 * 
 * @author chs 2014-10-20 version 1.0
 */
public class Utils {
	/**不为空判断*/
	public static boolean isNotNull(Object o) {
		if (o != null) {
			if (!"".equals(o) && !"null".equals(o)&&!"undefined".equals(o)) {
				return true;
			}
		}
		return false;
	}
	/***/
	public static String trimString(Object o){
		if(o==null||"".equals(o)||"null".equals(o)||"undefined".equals(o)){ 
			return ""; 
		}else{   
			return o.toString().trim(); 
		}
	}
	/**空判断*/
	public static boolean isNull(Object o){ 
		return !isNotNull(o);
	}
	private static String getSqlSplitString(String s) {
		if (s != null){
			return "'" + s.replaceAll(",", "','") + "'";
		}			
		return s;
	}
	/**用于SQL查询时，in()，建议串不宜过长(10个以内)，否则要换种思路来做  2014-10-23 chs add*/
	public static String getSqlSplitStr(String s) {
		return getSqlSplitString(s);   
	}
	
	/**explain String类型转换
	 * @author niujs 2014-11-24
	 * update niujs 2014-11-24
	 * @param o 要转换的元素
	 * @return String 转换后的string字符串
	 */
	public static String toString(Object o) {
		if(o != null) {
			return o.toString();
		} else {
			return "";
		}
	}
	
	/**
	 * explain 例:去除'aa','bb'格式为a,b 
	 * @author chs 2014-11-17
	 * update chs 2014-11-17
	 * @param s
	 * @return String
	 */
	public static String devSqlSplitString(String s){
		if(s!=null&&s.length()>2){ 
			return (s.substring(1,s.length()-1)).replace("','",",");
		}
		return s;
	}
	
	/**成功和失败都需要返回串时，可以根据自己的情况输入json串*/
	public static String returnJson(boolean isSuccess,String msg){
		return "{\"success\":"+isSuccess+",\"msg\":\""+msg+"\"}";
	}	
		
	public static String devExceptString(String s){
		return s.replaceAll(".*([';]+|(--)+).*", " ");
	}
	/**获取IP地址*/
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;

	}

	
	/**
	 * 将容易引起xss漏洞的半角字符直接替换成全角字符
	 * 
	 * @param s
	 * @return
	 */
	public static String xssEncode(String s) {
		if (s == null || "".equals(s)) {
			return s;
		}
		StringBuilder sb = new StringBuilder(s.length() + 16);
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '>':
				sb.append('＞');// 全角大于号
				break;
			case '<':
				sb.append('＜');// 全角小于号
				break;
			case '\'': 
				//sb.append('‘');// 全角单引号  
				break; 
			case '\"': 
				sb.append('“');// 全角双引号
				break;
			case '&':
				sb.append('＆');// 全角
				break;
			case '\\':
				sb.append('＼');// 全角斜线
				break;
			case '#':
				sb.append('＃');// 全角井号
				break;
			default:
				sb.append(c);
				break;
			}
		}
		String str = sb.toString();
		str = replaceBlank(str);
		str = replaceAll(str, "javascript:", "");
		str = replaceAll(str, "jscript:", "");
		str = replaceAll(str, "vbscript:", "");
		str = replaceAll(str, "script:", "");
		str = replaceAll(str, "select:", "");
		str = replaceAll(str, "document:", "");
		str = replaceAll(str, "cookie:", "");
		str = replaceAll(str, "alert:", "");
		
		return str;
	}

	/**
	 * 去 空白符
	 * @param source
	 * @return
	 */
	public static String replaceBlank(String source) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(source);
		return m.replaceAll("");
	}
	/**
	 * 替换字符串 ；大小写不敏感
	 * @param hexCharCodeStr
	 * @return  String
	 */
	public static String toStringHex(String hexCharCodeStr) { 
	   String trimedStr = hexCharCodeStr.trim();
	   String rawStr = trimedStr.substring(0,2).toLowerCase().equals("0x") 
                        ?  trimedStr.substring(2)
		                :  trimedStr;
	   byte[] baKeyword = new byte[rawStr.length()/2]; 
	   for(int i = 0; i < baKeyword.length; i++) { 
	      try { 
	     	baKeyword[i] = (byte)(0xff & Integer.parseInt(rawStr.substring(i*2, i*2+2),16)); 
	      }catch(Exception e) { 
	           e.printStackTrace(); 
	      } 
	   } 
	   try { 
		  rawStr = new String(baKeyword, "utf-8");//UTF-16le:Not 
	   } catch (Exception e1) { 
	    	e1.printStackTrace(); 
	   } 
		return rawStr; 
	} 
	public static String encrypt(String strOld, String strKey) {
		byte[] data = strOld.getBytes();
		byte[] keyData = strKey.getBytes();
		int keyIndex = 0 ;
		for(int x = 0 ; x < strOld.length() ; x++) {
	    	data[x] = (byte)(data[x] ^ keyData[keyIndex]);
		    if (++keyIndex == keyData.length){
		      keyIndex = 0;
		   }
	    }
		return new String(data);
	} 
	

	public static String en(String source, String miyue){
		String  last="";
		for (int i=0;i<source.length();i++) {
			 for (int j=0;j<miyue.length();j++) {
			 	 char key=miyue.charAt(j);
			 	 int text2=source.charAt(i)^key;				 
			 }
			 // last+=text2;
		}	
		return last;
	}
	
	
	/**
	 * 十六进制转换成字符串
	 * @param source
	 * @param oldStr
	 * @param newStr
	 * @return
	 */
	public static String replaceAll(String source, String oldStr, String newStr) {
		return source.replaceAll("(?i)" + oldStr, newStr);
	}
	
	

	
	
	 /** 密码验证
	 * 您的密码必须含有“小写字母”、“大写字母”、“数字”、“特殊符号”中的任意三种
	 * */
	public static boolean testPWD(String str){
		 if(str.length()<6||str.length()>20) {
			 return false;
		 }else{
			 boolean l=match(Constants.PWDTEST[0],str);
			 boolean u=match(Constants.PWDTEST[1],str);
			 boolean n=match(Constants.PWDTEST[2],str);
			 boolean s=match(Constants.PWDTEST[3],str);
			 if((l && u && n) || (l && u && s) || (s && u && n) || (s &&l && n)){
	                return true;
	          }else{
	                return false;
	          }
		 }
	}
	/**
	 * 是否包含汉字
	 * */
	public static boolean isContainChiness(String str){
		boolean l=match(Constants.CHINESS,str);
		return l;
	}
	/**
	 * 是否是数字
	 * */
	public static boolean isNum(String str){
		boolean l=matchall("[0-9 ]*",str);
		return l;
	}
    private static boolean match(String regex, String str) {
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(str);
			boolean b = matcher.find();
			return b;
	}
    public static boolean matchall(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		boolean b = matcher.matches();
		return b;
   }
    private static int charLength(String str){
    
       return str.replace("[^\\x00-\\xff]", "**").length();
    }
   
    
    /**
     * 获得字符集编码类型
     * @param str 
     * @return 返回字符编码类型
     */
    public static String getCharEncode(String str){
        String charEncode   = "UTF-8";
        try {
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){
            
                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {
        
        }
        charEncode = "GB2312";
        try {
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){
                
                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {
            
        }
        
        charEncode = "GBK";
        try {
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){
                
                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {
            
        }
        
        charEncode = "ISO-8859-1";
        try {
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){
                
                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {
            
        }
        
        charEncode = "UTF-8";
        try {
            if(str.equals(new String(str.getBytes(charEncode),charEncode))){
            
                return charEncode;
            }
        } catch (UnsupportedEncodingException e) {
        
        }
        
        return "";
        
    }
    
    /**
     * 转成GBK编码
     * @param str
     * @return
     */
    public static String transcodeToGBK(String str){
        return transcode(str,"GBK");
    }
    
    /**
     * 转成UTF-8编码
     * @param str
     * @return
     */
    public static String transcodeToUTF_8(String str){
        return transcode(str,"UTF-8");
    }
    
    /**
     * 自动转码
     * @param str
     * @param charEncode 默认UTF-8
     * @return
     */
    public static String transcode(String str,String charEncode){
        if(null==charEncode||"".equals(charEncode)){
            charEncode = "UTF-8";
        }
        String temp = "";
        try {
            String code = getCharEncode(str);
            temp = new String(str.getBytes(code),charEncode);
            code = getCharEncode(temp);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return temp;
    }
    
    public static String getIdsWithSingleQuotes(String sids) {
    	String cids = null;
		if (sids.indexOf(",") != -1) {
			String str[] = sids.split(",");
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < str.length; i++) {
				sb.append("'" + str[i] + "'");
				if (i < str.length - 1) {
					sb.append(",");
				}
			}
			cids = sb.toString();
		} else {
			cids = "'" + sids + "'";
		}
		return cids;
	}
    
    public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(
							src.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(
							src.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}
    
    
    
    /**
     * 字符串是否是手机号
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) { 
    	//Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$"); //比较严格 
    	Pattern p = Pattern.compile("^1[3|4|5|7|8]\\d{9}$");  //比较放松
    	Matcher m = p.matcher(phone);  
    	return m.matches();
	}
    
    
    /**
     * @描述 java生成流水号   18 位
     * 14位时间戳 + 4位随机数 
     * @return
     */
    public static String getTimeSerialNumber(){  
        String id="";  
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");  
        String temp = sf.format(new Date());  
        int random=(int) (Math.random()*10000);  
        id=temp+random;  
        return id;  
    }  
    
    
    
    
	public static void main(String[] args) {
	   System.out.println(Utils.getTimeSerialNumber().length());
	}
}
